package com.atguigu.redisspringboot2.service.impl;

import com.atguigu.redisspringboot2.entity.User;
import com.atguigu.redisspringboot2.mapper.UserMapper;
import com.atguigu.redisspringboot2.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @Autowired
    private UserMapper userMapper;
    @Override
    public List<User> getAllUsers() {
        long startTime = System.currentTimeMillis();
        String key = "userList";
        List<User> userList = null;
        if (redisTemplate.hasKey(key)) {
            userList = (List<User>) redisTemplate.opsForValue().get(key);
            long endTime = System.currentTimeMillis();
            System.out.println("Redis 查询数据耗时：" + (endTime - startTime) + "ms");
        }else {
            userList = userMapper.getAllUsers();
            long endTime = System.currentTimeMillis();
            System.out.println("mysql 查询数据耗时：" + (endTime - startTime) + "ms");
            redisTemplate.opsForValue().set(key,userList);
        }
        return userList;

    }
}
